<template>
  <div class="board-column">
    <div class="board-column-header" :style="{'color': color}">
      <i class="el-icon-s-opportunity" />
      {{ headerText }}
      <span>{{ myNum }}</span>
    </div>
    <!--list 内容-->
    <draggable
      v-infinite-scroll="scrollData"
      :infinite-scroll-disabled="disabled"
      :list="lists"
      v-bind="$attrs"
      class="board-column-content"
      :set-data="setData"
      :style="style"
      :move="move"
      @add="add"
      @end="end"
    >
      <div v-for="element in lists" v-show="lists && lists.length > 0" :key="element.id" class="board-item" @click="handleContent(element)">
        <div class="content">
          <div class="task-content-wrapper">
            <span v-if="element.name" class="taskName">{{ element.name }}</span>
            <span v-else class="taskName">-----</span>
            <span v-if="element.executorName" class="avatar">
              <el-tooltip :content="'执行人: ' + element.executorName" placement="top">
                <el-button type="text" size="mini">{{ element.executorName }}</el-button>
              </el-tooltip>
            </span>
          </div>
          <div class="task-infos">
            <span class="finishTime">{{ parseTime(element.deadlineDate) }}</span>
          </div>
        </div>
      </div>
      <p class="noTask">{{ loadTit }}</p>
      <p v-show="lists && lists.length === 0" class="noTask">{{ $t('暂无任务') }}</p>
    </draggable>

    <div class="addBoard" @click="addTask"><i class="el-icon-plus" /></div>

    <!-- add -->
    <el-dialog
      :title="$t('督办任务')"
      :visible.sync="formOpen"
      :close-on-click-modal="false"
      :lock-scroll="false"
      append-to-body
      width="60%"
      @close="cancel"
    >
      <!-- 亮牌操作 -->
      <el-form ref="form" :model="form" :rules="rules" class="dataForm">
        <el-row>
          <el-col :span="24">
            <div class="card" style="float:right">
              <el-button v-hasPermi="['deal:taskbase:brightCard']" type="warning" round @click="card('y',undefined)">黄色</el-button>
              <el-button v-hasPermi="['deal:taskbase:brightCard']" type="danger" round @click="card('r',undefined)">红色</el-button>
            </div>
          </el-col>
          <el-col :span="24">
            <el-form-item :label="$t('任务名称')" prop="name">
              <el-input v-model="form.name" :placeholder="$t('任务名称')" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('任务状态')" prop="taskStatus">
              <dictSelect
                v-model="form.taskStatus"
                :clearable="true"
                dictionary="task_status"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('跟进人')" prop="followPerson">
              <UserSelect
                v-model="form.followPerson"
                :placeholder="$t('跟进人')"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('执行人')" prop="executor">
              <UserSelect
                v-model="form.executor"
                :placeholder="$t('执行人')"
                @change="changeExecutor"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('完成期限')" prop="deadlineDate">
              <DatePicker v-model="form.deadlineDate" :placeholder="$t('完成期限')" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('执行部门')" prop="executiveDepartmentId">
              <treeSelect v-model="form.executiveDepartmentId" :default-expand-all="true" :data="deptOptions" :placeholder="$t('请选择')">
                <label slot="option-label" slot-scope="{ node, shouldShowCount, count, labelClassName, countClassName }" :class="labelClassName">
                  {{ $t(node.label) }}
                  <span v-if="shouldShowCount" :class="countClassName">({{ count }})</span>
                </label>
              </treeSelect>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('提醒频率')" prop="reminderFrequency">
              <el-input v-model="form.reminderFrequency" type="num" :placeholder="$t('提醒频率')" />
            </el-form-item>
          </el-col>
          <el-col v-hasPermi="['deal:taskbase:brightCard']" :span="12">
            <el-form-item :label="$t('是否亮牌')" prop="time">
              <el-select v-model="form.brightCard" :placeholder="$t('是否亮牌')" clearable disabled>
                <el-option key="r" value="r" label="红色">红色</el-option>
                <el-option key="y" value="y" label="黄色">黄色</el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 任务反馈情况 -->
        <div style="margin-top:15px;">
          <div class="area-header">
            <span class="area-header-title">{{ $t('任务反馈情况') }}</span>
          </div>
          <div>
            <el-table
              v-loading="fymxLoading"
              :data="form.executorFeedbacks"
              border
              class="nowrapTable formTable"
            >
              <el-table-column :label="$t('提醒日期')" align="center">
                <template slot="header" slot-scope="{}">
                  <i style="color: #ff4949;margin-right: 4px;">*</i>
                  <span>{{ $t('提醒日期') }}</span>
                </template>
                <template slot-scope="scope">
                  <el-form-item :prop="'executorFeedbacks.' + scope.$index + '.reminderDate'" :rules="formListCheck.reminderDate">
                    <DatePicker v-model="scope.row.reminderDate" :placeholder="$t('提醒日期')" />
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column :label="$t('当前任务状态')" align="center">
                <template slot="header" slot-scope="{}">
                  <i style="color: #ff4949;margin-right: 4px;">*</i>
                  <span>{{ $t('当前任务状态') }}</span>
                </template>
                <template slot-scope="scope">
                  <el-form-item :prop="'executorFeedbacks.' + scope.$index + '.currentTaskStatus'" :rules="formListCheck.currentTaskStatus">
                    <dictSelect
                      v-model="scope.row.currentTaskStatus"
                      :clearable="true"
                      dictionary="task_status"
                    />
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column :label="$t('汇报日期')" align="center">
                <template slot="header" slot-scope="{}">
                  <i style="color: #ff4949;margin-right: 4px;">*</i>
                  <span>{{ $t('汇报日期') }}</span>
                </template>
                <template slot-scope="scope">
                  <el-form-item :prop="'executorFeedbacks.' + scope.$index + '.reportDate'" :rules="formListCheck.reportDate">
                    <DatePicker v-model="scope.row.reportDate" :placeholder="$t('汇报日期')" />
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column :label="$t('汇报进度')" align="center">
                <template slot="header" slot-scope="{}">
                  <i style="color: #ff4949;margin-right: 4px;">*</i>
                  <span>{{ $t('汇报进度') }}</span>
                </template>
                <template slot-scope="scope">
                  <el-form-item :prop="'executorFeedbacks.' + scope.$index + '.taskProgress'" :rules="formListCheck.taskProgress">
                    <el-input
                      v-model="scope.row.taskProgress"
                      :placeholder="$t('汇报进度')"
                      show-word-limit
                    />
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column :label="$t('备注')" align="center">
                <template slot-scope="scope">
                  <el-form-item prop="note">
                    <el-input v-model="scope.row.remark" type="textarea" maxlength="200" class="fileTextarea" />
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column v-if="!executorFeedbacksHide" :label="$t('操作')" align="center" width="60px">
                <template slot-scope="scope">
                  <el-button size="small" type="text" icon="el-icon-delete" @click="delData(scope.$index)" />
                </template>
              </el-table-column>
            </el-table>
          </div>

          <div class="tol">
            <el-button type="primary" icon="el-icon-plus" size="mini" @click="addData">{{ $t("添加") }}</el-button>
          </div>
        </div>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">{{ $t("取消") }}</el-button>
        <el-button v-hasPermi="['deal:taskbase:edit']" type="primary" @click="submitForm">{{ $t("保存") }}</el-button>
      </div>
    </el-dialog>

    <!-- 查看 -->
    <el-dialog
      :title="$t('督办任务')"
      :visible.sync="taskOpen"
      :close-on-click-modal="false"
      :lock-scroll="false"
      append-to-body
      width="60%"
      @close="cancel"
    >
      <el-form ref="form" :model="form" class="dataForm">
        <el-row>
          <el-col :span="24">
            <div class="card" style="float:right">
              <el-button v-hasPermi="['deal:taskbase:brightCard']" type="warning" round @click="card('y',undefined)">黄色</el-button>
              <el-button v-hasPermi="['deal:taskbase:brightCard']" type="danger" round @click="card('r',undefined)">红色</el-button>
            </div>
          </el-col>
          <el-col :span="24">
            <el-form-item :label="$t('任务名称')" prop="name">
              <el-input v-model="form.name" :placeholder="$t('任务名称')" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('任务状态')" prop="taskStatus">
              <dictSelect
                v-model="form.taskStatus"
                :clearable="true"
                dictionary="task_status"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('跟进人')" prop="followPerson">
              <UserSelect
                v-model="form.followPerson"
                :placeholder="$t('跟进人')"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('执行人')" prop="executor">
              <UserSelect
                v-model="form.executor"
                :placeholder="$t('执行人')"

                @change="changeExecutor"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('完成期限')" prop="executionPeriod">
              <DatePicker v-model="form.deadlineDate" :placeholder="$t('完成期限')" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('执行部门')" prop="executiveDepartmentId">
              <treeSelect v-model="form.executiveDepartmentId" :default-expand-all="true" :data="deptOptions" :placeholder="$t('请选择')">
                <label slot="option-label" slot-scope="{ node, shouldShowCount, count, labelClassName, countClassName }" :class="labelClassName">
                  {{ $t(node.label) }}
                  <span v-if="shouldShowCount" :class="countClassName">({{ count }})</span>
                </label>
              </treeSelect>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('提醒频率')" prop="time">
              <el-input v-model="form.reminderFrequency" type="num" :placeholder="$t('提醒频率')" />
            </el-form-item>
          </el-col>
          <el-col v-hasPermi="['deal:taskbase:brightCard']" :span="12">
            <el-form-item :label="$t('是否亮牌')" prop="time">
              <el-select v-model="form.brightCard" :placeholder="$t('是否亮牌')" clearable disabled>
                <el-option key="r" value="r" label="红色">红色</el-option>
                <el-option key="y" value="y" label="黄色">黄色</el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 任务反馈情况 -->
        <div style="margin-top:15px;">
          <div class="area-header">
            <span class="area-header-title">{{ $t('任务反馈情况') }}</span>
          </div>
          <div>
            <el-table
              v-loading="fymxLoading"
              :data="form.executorFeedbacks"
              border
              class="nowrapTable formTable"
            >
              <el-table-column :label="$t('提醒日期')" align="center">
                <template slot="header" slot-scope="{}">
                  <i style="color: #ff4949;margin-right: 4px;">*</i>
                  <span>{{ $t('提醒日期') }}</span>
                </template>
                <template slot-scope="scope">
                  <el-form-item prop="reminderDate">
                    <DatePicker v-model="scope.row.reminderDate" :placeholder="$t('提醒日期')" />
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column :label="$t('当前任务状态')" align="center">
                <template slot-scope="scope">
                  <el-form-item prop="currentTaskStatus">
                    <dictSelect
                      v-model="scope.row.currentTaskStatus"
                      :clearable="true"
                      dictionary="task_status"
                    />
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column :label="$t('汇报日期')" align="center">
                <template slot="header" slot-scope="{}">
                  <i style="color: #ff4949;margin-right: 4px;">*</i>
                  <span>{{ $t('汇报日期') }}</span>
                </template>
                <template slot-scope="scope">
                  <el-form-item prop="reportDate">
                    <DatePicker v-model="scope.row.reportDate" :placeholder="$t('汇报日期')" />
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column :label="$t('汇报进度')" align="center">
                <template slot="header" slot-scope="{}">
                  <i style="color: #ff4949;margin-right: 4px;">*</i>
                  <span>{{ $t('汇报进度') }}</span>
                </template>
                <template slot-scope="scope">
                  <el-form-item prop="taskProgress">
                    <el-input
                      v-model="scope.row.taskProgress"
                      :placeholder="$t('汇报进度')"
                      show-word-limit
                    />
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column :label="$t('备注')" align="center">
                <template slot-scope="scope">
                  <el-form-item prop="note">
                    <el-input v-model="scope.row.remark" type="textarea" maxlength="200" class="fileTextarea" />
                  </el-form-item>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <div class="tol">
            <el-button type="primary" icon="el-icon-plus" size="mini" @click="addData">{{ $t("添加") }}</el-button>
          </div>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">{{ $t("取消") }}</el-button>
        <el-button v-hasPermi="['deal:taskbase:edit']" type="primary" @click="updateForm">{{ $t("保存") }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import draggable from 'vuedraggable'
import { getUser } from '@/api/system/user'
import { saveTaskBase, getTaskBase, listTaskBase, updateTaskBrightCard } from '@/api/deal/taskBase/taskBase'
import treeSelect from '@/components/TreeSelect/index'

export default {
  name: 'DragKanban',
  components: {
    draggable,
    treeSelect
  },
  props: {
    headerText: {
      type: String,
      default: 'Header'
    },
    color: {
      type: String,
      default: 'Header'
    },
    num: {
      type: Number,
      default: 0
    },
    code: {
      type: String,
      default: ''
    },
    options: {
      type: Object,
      default() {
        return {}
      }
    },
    param: {
      type: Object,
      default() {
        return {}
      }
    },
    list: {
      type: Array,
      default() {
        return []
      }
    },
    deptOptions: {
      type: Array,
      default() {
        return []
      }
    }

  },
  data() {
    const isInt = (rule, value, callback) => {
      if (value === undefined || value === '' || value === null) {
        callback(new Error('不能为空'))
      } else if (!Number(value)) {
        callback(new Error('请输入正整数'))
      } else {
        callback()
      }
    }
    return {
      style: {},
      loading: false,
      fymxLoading: false,
      lists: [],
      myNum: undefined,
      formOpen: false,
      taskOpen: false,
      form: {
        name: '',
        taskStatus: '',
        executiveDepartmentId: undefined,
        // 执行人反馈列表
        executorFeedbacks: [],
        brightCard: undefined
      },
      // 保存的时候用的因为没有id
      cardObj: undefined,
      executorFeedbacksHide: false,
      dataInfoCheck: {
        projectName: [{ required: true, message: this.$t('必填信息'), trigger: 'change' }]
      },
      temporaryVal: {
        deadlineDate: undefined
      },
      loadTit: '',
      rules: {
        name: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }],
        taskStatus: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }],
        followPerson: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }],
        executor: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }],
        deadlineDate: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }],
        reminderFrequency: [{ request: true, validator: isInt, trigger: 'blur' }, { required: true, message: this.$t('必填信息'),	trigger: 'blur' }],
        executiveDepartmentId: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }]
      },
      // 校验信息
      formListCheck: {
        reminderDate: [{ required: true, message: this.$t('必填信息'), trigger: 'change' }],
        currentTaskStatus: [{ required: true, message: this.$t('必填信息'), trigger: 'change' }],
        reportDate: [{ required: true, message: this.$t('必填信息'), trigger: 'change' }],
        taskProgress: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }]
      },
      notId: undefined
    }
  },
  computed: {
    disabled() {
      return this.loading
    }
  },
  watch: {
    list: {
      handler(val) {
        this.lists = val
      },
      deep: true,
      immediate: true
    },
    num: {
      handler(val) {
        this.myNum = val
      },
      deep: true,
      immediate: true
    }
  },
  created() {
  },
  mounted() {
    window.onresize = () => {
      return (() => {
        this.load()
      })()
    }
    this.$nextTick(() => {
      this.load()
    })
  },
  methods: {
    load() {
      const height = window.innerHeight - 200
      this.style = {
        'max-height': height + 'px'
      }
    },
    setData(dataTransfer) {
      dataTransfer.setData('Text', '')
    },
    // 打开新增页面
    addTask() {
      this.form.taskStatus = this.code
      this.formOpen = true
    },
    // 关闭新增页面
    cancel() {
      this.form = {
        name: '',
        taskStatus: '',
        executiveDepartmentId: undefined,
        // 执行人反馈列表
        executorFeedbacks: []
      }
      this.formOpen = false
      this.taskOpen = false
      this.cardObj = undefined
    },
    // 新增
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          const row = {
            id: this.form.id,
            name: this.form.name,
            createUserId: this.form.createUserId,
            followPerson: this.form.followPerson,
            executor: this.form.executor,
            executiveDepartmentId: this.form.executiveDepartmentId,
            executionPeriod: this.form.executionPeriod,
            deadlineDate: this.form.deadlineDate,
            reminderFrequency: this.form.reminderFrequency,
            taskStatus: this.form.taskStatus,
            executorFeedbacks: this.form.executorFeedbacks
          }
          this.$nextTick(() => {
            saveTaskBase(row).then(response => {
              if (response.code === 200) {
                this.msgSuccess(this.$t('保存成功'))
                this.lists.push(response.data)
                this.$emit('update:list', response.lists)
                this.formOpen = false
                this.taskOpen = false
                this.myNum++
                // 亮牌操作
                this.card(undefined, response.data.id)
              } else {
                this.msgError(response.msg)
              }
            })
          })
        }
      })
    },
    // 修改
    updateForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          const row = {
            id: this.form.id,
            name: this.form.name,
            createUserId: this.form.createUserId,
            followPerson: this.form.followPerson,
            executor: this.form.executor,
            executiveDepartmentId: this.form.executiveDepartmentId,
            executionPeriod: this.form.executionPeriod,
            deadlineDate: this.form.deadlineDate,
            reminderFrequency: this.form.reminderFrequency,
            taskStatus: this.form.taskStatus,
            executorFeedbacks: this.form.executorFeedbacks
          }
          this.$nextTick(() => {
            saveTaskBase(row).then(response => {
              if (response.code === 200) {
                this.msgSuccess(this.$t('保存成功'))
                this.lists.push(response.data)
                this.lists = this.unique(this.lists)
                this.$emit('update:list', response.lists)
                this.taskOpen = false
                this.cardObj = undefined
              } else {
                this.msgError(response.msg)
              }
            })
            //
          })
        }
      })
    },
    // 查看元素
    handleContent(row) {
      this.form = row
      this.taskOpen = true
      this.showTask(row.id)
    },
    // 执行人改变，修改执行部门
    changeExecutor() {
      const executor = this.form.executor
      if (executor === undefined || executor === '') {
        return
      }
      getUser(executor).then(response => {
        this.form.executiveDepartmentId = response.data.deptId
      })
    },
    // 删除任务反馈列表
    delData(index) {
      this.form.executorFeedbacks.splice(index, 1)
    },
    // 添加项目信息
    addData() {
      const row = {
        id: '',
        reminderDate: '',
        currentTaskStatus: '',
        reportDate: '',
        taskProgress: '',
        warningOrNot: ''
      }
      if (!(this.form.executorFeedbacks instanceof Array)) {
        this.$set(this.form, 'executorFeedbacks', [])
      }
      this.$nextTick(() => {
        this.form.executorFeedbacks.push(row)
      })
    },

    // 根据id回显数据
    showTask(id) {
      getTaskBase(id).then(response => {
        if (response.code === 200) {
          this.form = response.data
          this.taskOpen = true
        } else {
          this.msgError(response.msg)
        }
      })
    },
    // 滚动条事件
    scrollData() {
      this.$nextTick(() => {
        // if (this.myNum === 31) {
        //   debugger
        // }
        if (this.lists.length === 1 && this.myNum === 1) {
          return
        }
        this.param.pageNum++
        this.param.taskStatus = this.code
        if (this.lists.length < this.myNum) {
          this.getList(true, this.param)
        }
        console.log(this.param.pageNum)
        console.log(this.lists.length)
      })
    },
    // 滚动条事件
    getList(flag, param) {
      this.loading = true
        listTaskBase(param).then(response => {
          if (response.code === 200 && flag) {
            this.lists = this.unique(this.lists.concat(response.rows))
            // 多次加载数据
            if (this.lists.length >= response.total && response.total !== 0) {
              this.loadTit = this.$t('没有更多了')
              this.loading = false
            }
            if (response.total === 0) {
              this.loadTit = ''
              this.isLoading = false
              this.loading = false
              this.loadTit = ''
            }
            this.loading = false
          } else {
            // 第一次加载
            this.lists = response.rows
            this.total = response.total
            this.loading = false
          }
        })
    },
    // 拖拽 添加事件
    add() {
      this.$parent.upataData(this.code)
      this.myNum++
    },
    // 拖拽 结束事件
    end() {
      this.$nextTick(() => {
        this.param.pageNum = Number(this.param.pageNum / this.param.pageSize).toFixed(0)
        if (this.myNum > 0) {
          this.myNum--
          if (this.param.pageSize <= this.lists.length) {
            return
          }
          if (this.myNum === 0) {
            this.loadTit = ''
          }
          this.scrollData()
        }
      })
    },
    // 拖拽 移动事件 获取 id
    move(e) {
      this.notId = e.draggedContext.element.id
      this.$parent.getUpdataId(e.draggedContext.element.id)
    },
    // array去重
    unique(arr) {
      const res = new Map()
      return arr.filter((arr) => !res.has(arr.id) && res.set(arr.id, 1))
    },
    // 亮牌操作
    card(val, id) {
      console.log(this.cardObj)
      if (val !== undefined && val !== '') {
        this.cardObj = val
      }
      if (id !== undefined && id !== '') {
        this.form.id = id
      }
      this.form.brightCard = this.cardObj
      console.log(this.form.brightCard)
      if (this.form.id !== undefined && this.form.id !== '' && this.cardObj !== undefined && this.cardObj !== '') {
        const param = {
          brightCard: this.cardObj,
          id: this.form.id
        }
        updateTaskBrightCard(param).then(response => {
          const h = this.$createElement
          if (response.code === 200) {
            let color
            if (val === 'r') {
              color = '红色'
            } else {
              color = '黄色'
            }
            this.msgSuccess(this.$t('亮牌成功' + color))
          } else {
            this.$notify({
              title: '亮牌失败',
              message: h('i', { style: 'color: teal' }, '亮牌失败：' + response.msg)
            })
          }
        })
        this.cardObj = undefined
      }
    }

  }

}
</script>
<style scoped>
.el-select {
  width: 100%;
}

.task-context {
  height: 30px;
}

.draggable {
  width: 100%;
}
.spancolor{
  width:30px;
  height:30px;
  border-radius: 50%;
  display: block;
  margin: 0 auto;
}

</style>
